import { SessionService } from '../../services/session-service';
import { CompanyService } from '../../services/company-service';
import { LocationService } from '../../services/location-service';
import { ProjectService } from '../../services/project-service';
import {
    Building,
    Company,
    Floor,
    Location,
    Project,
    Unit
} from '../model/defination';
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

type selectedId = {
    project?: number;
    building: number;
    floor: number;
    unit: number;
    company?: number;
};

@Component({
    selector: 'location-select',
    templateUrl: './location-select.component.html',
    styleUrls: ['./location-select.component.scss'],
    providers: [LocationService, CompanyService]
})
export class LocationSelectComponent implements OnInit {
    _data: Array<Location>;

    @Input() showTable = true;

    @Input() static = false;

    @Input() hasCompany = false;

    @Output() DataChange: EventEmitter<any> = new EventEmitter<any>(true);

    @Output() CompanyChange: EventEmitter<any> = new EventEmitter<any>(true);

    get IsAdmin() {
        return this._sessionService.isUserAdmin;
    }

    get IsProperty() {
        return this._sessionService.isUserProperty;
    }

    get IsHr() {
        return this._sessionService.isUserHr;
    }

    @Input() show: boolean = false;

    @Input() isOpen = false;

    @Input()
    set Data(val) {
        this._data = val || [];
        this.DataChange.emit(val);
    }

    get Data() {
        return this._data;
    }

    _company: Company;

    @Input()
    set Company(val) {
        this._company = val;
        this.CompanyChange.emit(val);
    }

    get Company() {
        return this._company;
    }
    get IsSelectValid() {
        return (
            this.selected.building &&
            this.selected.project &&
            this.selected.unit &&
            this.selected.floor
        );
    }
    isValid() {
        return (
            this.selected.building &&
            this.selected.project &&
            this.selected.unit &&
            this.selected.floor
        );
    }
    selected: selectedId = {
        project: -1,
        building: -1,
        floor: -1,
        unit: -1,
        company: -1
    };

    projects: Array<Project> = [
        {
            name: '加载中',
            locationCode: '23'
        }
    ];

    buildings: Array<Building> = [
        {
            buildingAlias: '加载中...',
            buildingNumber: '1',
            projectId: -1
        }
    ];

    floors: Array<Floor> = [
        {
            buildingId: -1,
            index: '加载中...'
        }
    ];

    units: Array<Unit> = [
        {
            name: '加载中...',
            floorId: 1
        }
    ];

    companies: Array<any> = [
        {
            name: '加载中...'
        }
    ];

    constructor(
        private _projectService: ProjectService,
        private _locationService: LocationService,
        private _companyService: CompanyService,
        private _sessionService: SessionService
    ) {}

    async ngOnInit() {
        this.projects = await this._projectService.All().toPromise();
        console.log(this.projects);
        if (this.IsProperty) {
            // 固定项目,不显示项目选择
            this.selected.project = this._sessionService.Managable.id;
            await this.projectChange(null);
        }
    }

    async deleteLocation(index: number) {
        const location = this.Data[index];
        // await this._locationService.Delete(location.id).toPromise();
        this.Data.splice(index, 1);
    }

    private _isLocationExist(location) {
        const cond = d =>
            d.project.id === this.selected.project &&
            d.building.id === this.selected.building &&
            d.floor.id === this.selected.unit;

        const ret = this.Data.find(cond);
        return typeof ret !== 'undefined';
    }

    async projectChange(event) {
        this.selected.building = this.selected.floor = this.selected.unit = -1;
        this.buildings = await this._locationService
            .getAllBuildingsByProjectId(this.selected.project)
            .toPromise();
    }

    async buildingChange(event) {
        this.selected.floor = this.selected.unit = -1;
        this.floors = await this._locationService
            .getAllFloorsByBuildingId(this.selected.building)
            .toPromise();
    }

    async floorChange() {
        this.selected.unit = -1;
        this.units = await this._locationService
            .getAllUnitsByFloorId(this.selected.floor)
            .toPromise();
    }

    async unitChange() {
        const req = await this._companyService
            .getCompanybyUnitId(this.selected.unit)
            .toPromise();
        this.companies = req.items;
        this.selected.company =
            this.companies && this.companies.length ? this.companies[0].id : -1;
        const emitCompany: any = req.items.length
            ? req.items
            : [{ name: '未找到此单元的公司信息，请联系管理员!' }];
        this.CompanyChange.emit(emitCompany);
    }
    async addLocation() {
        // if (typeof this.IsSelectValid === 'undefined') {
        //     return false;
        // }

        if (!this.isValid()) {
            return false;
        }

        const location: any = {
            projectId: this.selected.project,
            buildingId: this.selected.building,
            floorId: this.selected.floor,
            unitId: this.selected.unit
        };
        if (this._isLocationExist(location)) {
            alert('地址已存在，请勿重复添加!');
            return false;
        }
        const resp: Location = await this._locationService
            .Create(location)
            .toPromise();

        this.Data.push(resp);
        if (this._sessionService.isUserProperty) {
            this.selected.building = -1;
            this.selected.floor = -1;
            this.selected.unit = -1;
        } else {
            this.selected = {
                project: -1,
                building: -1,
                floor: -1,
                unit: -1
            };
        }
    }
}
